// 导入数据库模块
const db = require('../db/index')



// 查询所有菜单，然后递归遍历出子菜单
function queryAllMenus(menusList){
    let result = []
    menusList.forEach(menus => {
        findChildMenu(menusList, menus)
        if(menus.parentId == -1){
            // console.log(menus);
            result.push(menus);
        }
    });
    return result
}


function findChildMenu(menusList, menus){
    menusList.forEach(item => {
        if(item.parentId == menus.id){
            let childMenus = getChildMenus(menus, menusList);
            if (childMenus == null) {
                childMenus = [];
            }
            if (!containsMenus(childMenus, item)) {
                childMenus.push(item);
            }

            setChildMenus(menus,childMenus);
        }
    });
}


function getChildMenus(menus, menusList){
    let childMenus = []
    
    menusList.forEach(element => {
        if(menus.id == element.parentId){
            childMenus.push(element)
        }
    });
    return childMenus

}



function containsMenus(childMenus, item){
    let flag = false
    childMenus.forEach(element => {
        if(element.id == item.id){
            flag = true
        }
    });
    return flag

}



function setChildMenus(menus,childMenus){
    menus.children = childMenus
    
}



// 获取侧边栏菜单
exports.getMenus = (req, res)=>{
    const sql = 'select id, title, indexPath, icon, parentId, rootId, weight from ev_menus order by weight'
    db.query(sql, (err, results)=>{
        if(err){
            return res.cc(err)
        }
        //
        // res.send({
        //     status: 0,
        //     message: '获取左侧菜单成功！',
        //     data: results

        // })

        const data = queryAllMenus(results)
        res.send({
            status: 0,
            message: '获取左侧菜单成功！',
            data: data

        })

    })
}